<template>
  <BasicDrawer
    title="数据权限"
    width="60%"
    @register="register"
    :showFooter="true"
    @ok="handleOk"
    @close="handleCancel"
    destroyOnClose
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script setup>
  import { nextTick, ref } from 'vue';
  import { useDrawer, BasicDrawer } from '/@/components/Drawer';
  import { BasicForm, useForm } from '/@/components/Form';
  import { grantDataScope } from '/@/api/sys/role';
  import { message } from 'ant-design-vue';
  import { findNodeById } from '/@/utils/tree';
  const isSave = ref(true);
  const treeData = ref([]);
  const emits = defineEmits(['success']);
  // 注册表单
  const [registerForm, { setFieldsValue, getFieldsValue }] = useForm({
    labelWidth: 80,
    showResetButton: false,
    showSubmitButton: false,
    schemas: [
      {
        field: 'name',
        label: '角色名称',
        component: 'Input',
        colProps: {
          xl: 24,
          xxl: 24,
        },
        componentProps: {
          disabled: true,
          placeholder: '请输入角色名称',
        },
      },
      {
        field: 'code',
        label: '唯一编码',
        component: 'Input',
        colProps: {
          xl: 24,
          xxl: 24,
        },
        componentProps: {
          disabled: true,
          placeholder: '请输入唯一编码',
        },
      },
      {
        field: 'dataScope',
        label: '数据范围',
        component: 'ApiDict',
        colProps: {
          xl: 24,
          xxl: 24,
        },
        componentProps: {
          placeholder: '请选择数据范围',
          code: 'sys_role_data_scope',
        },
      },
      {
        field: 'deptIdList',
        label: '数据权限',
        component: 'ApiTreeSelect',
        colProps: {
          xl: 18,
          xxl: 18,
        },
        ifShow: ({ values }) => {
          return values?.dataScope == 2;
        },
        componentProps: ({ formModel }) => {
          if (formModel.treeCheckStrictly === 1) {
            // 父子关联
            formModel.deptIdList = formModel.deptIdList?.map((item) => item.value || item);
          } else {
            formModel.deptIdList = formModel.deptIdList?.map((item) => {
              const value = item.value || item;
              const node = findNodeById(treeData.value, value);
              return {
                value: value,
                label: node?.name || value,
              };
            });
          }
          return {
            api: '/sys/dept/tree',
            placeholder: '请选择数据权限',
            allowClear: true,
            replaceFields: {
              title: 'name',
              value: 'id',
              key: 'id',
            },
            onOptionsChange(data) {
              treeData.value = data;
            },
            labelInValue: false,
            multiple: true,
            treeCheckable: true,
            treeCheckStrictly: formModel.treeCheckStrictly != 1,
            maxTagCount: 1000,
            dropdownStyle: {
              maxHeight: '500px',
              overflow: 'auto',
            },
          };
        },
      },
      {
        field: 'treeCheckStrictly',
        label: '父子关联',
        component: 'ApiDict',
        colProps: {
          xl: 6,
          xxl: 6,
        },
        ifShow: ({ values }) => {
          return values?.dataScope == 2;
        },
        defaultValue: 0,
        componentProps: {
          isBtn: true,
          renderType: 'RadioGroup',
          code: 'yes_no',
        },
      },
    ],
  });
  const currentRecord = ref();
  const [register, { openDrawer }] = useDrawer();
  const handleCancel = () => {
    if (isSave.value) {
      emits('success');
    }
  };
  /**
   * 处理提交保存
   */
  const handleOk = () => {
    const values = getFieldsValue();
    if (
      Array.isArray(values.deptIdList) &&
      values.deptIdList.length > 0 && // 判断deptIdList是否为普通数组[1,2,3]，还是对象数组，[{value:xx,label:xxx}]
      values.deptIdList[0].label !== undefined
    ) {
      values.deptIdList = values.deptIdList.map((item) => item.value);
    }
    grantDataScope({
      id: currentRecord.value.id,
      ...values,
    }).then(() => {
      isSave.value = true;
      message.success('保存成功');
    });
  };
  defineExpose({
    show(record) {
      currentRecord.value = record;
      isSave.value = false;
      openDrawer();
      nextTick(() => {
        setFieldsValue({
          name: record.name,
          code: record.code,
          dataScope: record.dataScope,
          deptIdList: record.deptIdList,
        });
      });
    },
  });
</script>
